package com.argrace.smart.activity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.SystemClock;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.util.Log;
import android.view.View;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.alink.business.alink.ALinkBusinessEx;
import com.aliyun.alink.sdk.net.anet.api.AError;
import com.aliyun.alink.sdk.net.anet.api.transitorynet.TransitoryRequest;
import com.aliyun.alink.sdk.net.anet.api.transitorynet.TransitoryResponse;
import com.argrace.smart.R;
import com.argrace.smart.adapter.SubDeviceListAdapter;
import com.argrace.smart.base.BaseActivity;
import com.argrace.smart.base.ConstantConfigure;
import com.argrace.smart.entity.MineZigBeeDeviceListEntity;
import com.argrace.smart.entity.ZigBeeDeviceDetailEntity;
import com.argrace.smart.model.LocalDb_DeviceNameAndRoomNameTable;
import com.argrace.smart.ui.EmptyRecycleView;
import com.argrace.smart.util.AlinkHttpUtil;
import com.argrace.smart.util.Logg;
import com.chad.library.adapter.base.BaseQuickAdapter;

import org.litepal.crud.DataSupport;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * Created by argrace_dev_1 on 2018/1/30.
 * 网关下面绑定的子设备列表，即绑定了网关的zigbee设备列表，右上角添加设备，进入厂商列表
 */

public class SubDeviceListActivity extends BaseActivity implements SwipeRefreshLayout.OnRefreshListener, BaseQuickAdapter.RequestLoadMoreListener {
    EmptyRecycleView recyclerView;
    SwipeRefreshLayout refreshLayout;
    private SubDeviceListAdapter adapter;
    private ArrayList<MineZigBeeDeviceListEntity> lists = new ArrayList<>();
    private String uuid, model;
    private int pageNo = 1;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_subdevicelist);
        init();
    }

    private void init() {
        uuid = getIntent().getStringExtra("uuid");
        model = getIntent().getStringExtra("model");
        Log.i("info", "SubDeviceListActivity.init(),uuid = " + uuid + "---model=" + model);
        setView();
        setTitle(true, false, "添加子设备");
        showRight(true, R.mipmap.head_title_add);
        //进入搜索产品子设备列表
        setLeftandRightClickListeners(null, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(SubDeviceListActivity.this, ProductListActivity.class);
                intent.putExtra("uuid", uuid);
                intent.putExtra("model", model);
                intent.putExtra("length", lists.size());
                startActivity(intent);
            }
        });
        setRefreshing(true);
        onRefresh();
    }

    @SuppressLint("ResourceType")
    private void setView() {
        recyclerView = (EmptyRecycleView) findViewById(R.id.recyclerView);
        refreshLayout = (SwipeRefreshLayout) findViewById(R.id.refreshLayout);
//        recyclerView.setItemAnimator(new DefaultItemAnimator());
        recyclerView.setItemAnimator(null);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        adapter = new SubDeviceListAdapter(lists, this);
        adapter.openLoadAnimation(BaseQuickAdapter.ALPHAIN);
        adapter.isFirstOnly(false);
        recyclerView.setAdapter(adapter);
        refreshLayout.setColorSchemeColors(getResources().getColor(R.color.colorPrimary), getResources().getColor(R.color.colorPrimary), getResources().getColor(R.color.colorPrimary));//getResources().getColor(R.color.colorTheme), getResources().getColor(R.color.colorTheme), getResources().getColor(R.color.colorTheme)
        refreshLayout.setOnRefreshListener(this);
        adapter.setOnLoadMoreListener(this);
        adapter.setlongListeners(new SubDeviceListAdapter.OnAdapterItemLongClickListener() {
            @Override
            public void click(MineZigBeeDeviceListEntity bean, int position) {
                getZigBeeDeviceinfo(bean);
            }
        });
        adapter.setListeners(new SubDeviceListAdapter.OnAdapterItemClickListener() {
            @Override
            public void click(MineZigBeeDeviceListEntity bean, int position) {
                Intent intent;
                //开关控制界面
                if (bean.getModel().equals(ConstantConfigure.MODEL_SANWEIDUOKONG)
                        || bean.getModel().equals(ConstantConfigure.MODEL_LIANGWEIDUOKONG)
                        || bean.getModel().equals(ConstantConfigure.MODEL_YIWEIDUOKONG)
                        ) {
                    intent = new Intent(SubDeviceListActivity.this, DeviceControl_KaiguanActivity.class);
//                    intent = new Intent(SubDeviceListActivity.this, DeviceRelation_KaiGuanActivity.class);
                    intent.putExtra("deviceinfo", bean);
                }
                //场景开关
                else if (bean.getModel().equals(ConstantConfigure.MODEL_SANWEIFUKONG)
                        || bean.getModel().equals(ConstantConfigure.MODEL_LIANGWEIFUKONG)
                        || bean.getModel().equals(ConstantConfigure.MODEL_YIWEIFUKONG)
                        || bean.getModel().equals(ConstantConfigure.MODEL_CHANGJINGKAIGUAN)
                        ) {
                    intent = new Intent(SubDeviceListActivity.this, DeviceControl_FuKongActivity.class);
                    intent.putExtra("deviceinfo", bean);
                }
                //烟雾、门磁、煤气（气体探测器）,红外感应（水地暖移除）,后加入水浸
                else if (bean.getModel().equals(ConstantConfigure.MODEL_YANWUTANCEQI) || bean.getModel().equals(ConstantConfigure.MODEL_MENCIGANYING) || bean.getModel().equals(ConstantConfigure.MODEL_MEIQITANCEQI) || bean.getModel().equals(ConstantConfigure.MODEL_RENTIGANYING) || bean.getModel().equals(ConstantConfigure.MODEL_SUIJINTANCEQI)) {
                    intent = new Intent(SubDeviceListActivity.this, DeviceControl_BaoJingActivity.class);
//                    intent = new Intent(SubDeviceListActivity.this, DeviceRelation_BaoJingActivity.class);
                    intent.putExtra("deviceinfo", bean);
                } else if (bean.getModel().equals(ConstantConfigure.MODEL_XINFENGKONGZHIQI)) {
                    intent = new Intent(SubDeviceListActivity.this, DeviceControl_XinFengKongZhiQi.class);
//                    intent = new Intent(SubDeviceListActivity.this, DeviceRelation_XinFengKongZhiQiActivity.class);
                    intent.putExtra("deviceinfo", bean);
                } else if (bean.getModel().equals(ConstantConfigure.MODEL_SHUIDINUAN) || bean.getModel().equals(ConstantConfigure.MODEL_DIANDINUAN)) {
                    intent = new Intent(SubDeviceListActivity.this, DeviceControl_ShuidinuanActivity.class);
//                    intent = new Intent(SubDeviceListActivity.this, DeviceRelation_ShuidinuanActivity.class);
                    intent.putExtra("deviceinfo", bean);
                } else if (bean.getModel().equals(ConstantConfigure.MODEL_PM25CHUANGANQI) || bean.getModel().equals(ConstantConfigure.MODEL_KONGQIHEZI)) {
                    intent = new Intent(SubDeviceListActivity.this, DeviceControl_PM25Activity.class);
//                    intent = new Intent(SubDeviceListActivity.this, DeviceRelation_PM25Activity.class);
                    intent.putExtra("deviceinfo", bean);
                } else if (bean.getModel().equals(ConstantConfigure.MODEL_10ACHAZUO)) {
                    intent = new Intent(SubDeviceListActivity.this, DeviceControl_ChaZuoActivity.class);
//                    intent = new Intent(SubDeviceListActivity.this, DeviceRelation_ChaZuoActivity.class);
                    intent.putExtra("deviceinfo", bean);
                } else if (bean.getModel().equals(ConstantConfigure.MODEL_ZHINENGMENSUO)) {
                    intent = new Intent(SubDeviceListActivity.this, DeviceControl_MenSuoActivity.class);
                    intent.putExtra("deviceinfo", bean);
                } else if (bean.getModel().equals(ConstantConfigure.MODEL_KAIHELIANDIANJI)) {
                    intent = new Intent(SubDeviceListActivity.this, DeviceControl_ChuangLianActivity.class);
//                    intent = new Intent(SubDeviceListActivity.this, DeviceRelation_ChuangLianActivity.class);
                    intent.putExtra("deviceinfo", bean);
                } else if (bean.getModel().equals(ConstantConfigure.MODEL_KONGTIAOZHUANHUANQI)) {
                    intent = new Intent(SubDeviceListActivity.this, DeviceControl_AirConditionActivity.class);
                    intent.putExtra("deviceinfo", bean);
                } else {
                    intent = new Intent(SubDeviceListActivity.this, MyDeviceControlActivity.class);
                    intent.putExtra("deviceinfo", bean);
                }
                intent.putExtra("model", bean.getModel());
                startActivity(intent);
            }
        });
    }

    //由于删除接口没有sn或者mac，先根据uuid查询设备详细信息，在执行删除
    private void getZigBeeDeviceinfo(MineZigBeeDeviceListEntity bean) {
        Logg.i("info", "进行删除子设备,第一步查询设备详情获取mac或者sn");
        String method = "mtop.openalink.app.core.device.getdetail";
        HashMap<String, Object> params = new HashMap<>();
        params.put("uuid", bean.getUuid());
        AlinkHttpUtil.AlinkHttpRequest(method, params, new ALinkBusinessEx.IListener() {
            @Override
            public void onSuccess(TransitoryRequest transitoryRequest, TransitoryResponse transitoryResponse) {
                Logg.i("info", "子设备详情成功" + transitoryResponse.data);
                ZigBeeDeviceDetailEntity bean = JSON.parseObject((String) transitoryResponse.data, ZigBeeDeviceDetailEntity.class);
                //查询到设备后进行移除
                removeZigBeeDevice(bean);
            }

            @Override
            public void onFailed(TransitoryRequest transitoryRequest, AError aError) {
                Log.i("info", "子设备详情失败" + aError.getMsg() + aError.getCode());
            }
        });
    }

    private void removeZigBeeDevice(ZigBeeDeviceDetailEntity bean) {
        String method = "mtop.openalink.app.core.device.requestremoteservice";
        HashMap<String, Object> params = new HashMap<>();
        if (bean.getSn() != null && !bean.getSn().equals("")) {
            params.put("args", "{\"sn\":\"" + bean.getSn() + "\"}");
            params.put("uuid", uuid);
            params.put("service", "RemoveDevice");
        }
        AlinkHttpUtil.AlinkHttpRequest(method, params, new ALinkBusinessEx.IListener() {
            @Override
            public void onSuccess(TransitoryRequest transitoryRequest, TransitoryResponse transitoryResponse) {
                Log.i("info", "子设备移除成功" + transitoryResponse.data);
                SystemClock.sleep(500);
                setRefreshing(true);
                onRefresh();
            }

            @Override
            public void onFailed(TransitoryRequest transitoryRequest, AError aError) {
                Log.i("info", "子设备移除失败" + aError.getMsg() + aError.getCode());
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    public void onRefresh() {
        setRefreshing(true);
        pageNo = 1;
        getSubDevicelist();
    }

    @Override
    public void onLoadMoreRequested() {
        pageNo++;
        getSubDevicelist();
    }

    public void setRefreshing(final boolean refreshing) {
        refreshLayout.post(new Runnable() {
            @Override
            public void run() {
                refreshLayout.setRefreshing(refreshing);
            }
        });
    }

    //查询子设备列表
    private void getSubDevicelist() {
        Log.i("info", "SubDeviceListActivity.getSubDevicelist(),start,uuid = " + uuid);
        String method = "mtop.openalink.home.device.infolist";
        HashMap<String, Object> params = new HashMap<>();
        params.put("uuid", uuid);
        params.put("pageNo", pageNo);
        params.put("pageSize", "10");
        AlinkHttpUtil.AlinkHttpRequest(method, params, new ALinkBusinessEx.IListener() {
            @Override
            public void onSuccess(TransitoryRequest transitoryRequest, TransitoryResponse transitoryResponse) {
                JSONObject dataObj = JSON.parseObject(transitoryResponse.data.toString());
                Logg.i("info", "子设备列表获取成功data=" + dataObj.toJSONString());
                List<MineZigBeeDeviceListEntity> beans = JSON.parseArray(dataObj.getString("deviceList"), MineZigBeeDeviceListEntity.class);
                if (beans == null || beans.size() == 0) {

                    setRefreshing(false);
                    adapter.loadMoreEnd();
//                    adapter.notifyDataSetChanged();
                } else {
                    for (int i = 0; i < beans.size(); i++) {
                        List<LocalDb_DeviceNameAndRoomNameTable> beans_local = DataSupport.where("uuid = ?", beans.get(i).getUuid()).find(LocalDb_DeviceNameAndRoomNameTable.class);
                        if (beans_local != null && beans_local.size() > 0) {
                            beans.get(i).setName(beans_local.get(0).getNickName());
                        }
                    }
                    if (pageNo == 1) {
                        lists.clear();
                        lists.addAll(beans);
                        adapter.setNewData(lists);
                        setRefreshing(false);
                        adapter.loadMoreComplete();
                    } else {
                        adapter.addData(beans);
                        setRefreshing(false);
                        adapter.loadMoreComplete();
                    }

                }


            }

            @Override
            public void onFailed(TransitoryRequest transitoryRequest, AError aError) {
                setRefreshing(false);
                if (pageNo > 1) {
                    pageNo--;
                }
                adapter.loadMoreFail();
                Log.i("info", "获取子设备列表失败,msg = " + aError.getMsg() + aError.getCode());
            }
        });

    }

    @Override
    protected void dorecieve(JSONObject obj) {
        super.dorecieve(obj);
        try {
            String value = obj.getJSONObject("params").getJSONObject("data").getJSONObject("Refresh").getString("value");
            //2说明是子设备入网成功推送
            if (value != null && value.equals("2")) {
                //子设备入网成功操作
                onRefresh();
            }
        } catch (Exception e) {

        }
    }
}
